import random


from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, redirect
from django.views.decorators.http import require_http_methods
from django_redis import get_redis_connection

from app01 import models
from app01.utils.script.response import BaseResponse
from app01.forms.account import LoginForms,MobileForms,SmsForms,SmsLoginForms,AddLevelForms




def login(request):
    if request.method == 'GET':
        form = LoginForms()
        return render(request, 'login.html',{"form":form})

    form = LoginForms(data=request.POST)
    if not form.is_valid():
        return render(request, 'login.html',{"form":form})
    # print(request.POST)
    print(form.cleaned_data)
    data_dict = form.cleaned_data
    role = data_dict.pop("role")
    # username = form.cleaned_data.get("name")
    # password = form.cleaned_data.get("password")
    # role = form.cleaned_data.get("role")
    mapping = {"1": "ADMIN", "2": "CUSTOMER"}
    # if role not in mapping:
    #     form.add_error("role","角色不存在")
    #     return render(request, 'login.html', {"form": form})
    if role == "1":
        user_objects = models.Administrator.objects.filter(**data_dict).first()
    else:
        user_objects = models.Customer.objects.filter(**data_dict).first()
    if not user_objects:
        form.add_error("password","用户名或密码错误")
        return render(request, 'login.html',{"form":form})
    request.session['user_info'] = {'role': mapping[role], 'name': user_objects.name, 'id': user_objects.id}
    return redirect("/home/")

def sms_send(request):
    res = BaseResponse()
    form = MobileForms(data=request.POST)
    if not form.is_valid():
        res.detail = form.errors
        return JsonResponse(res.dict,json_dumps_params={'ensure_ascii': False})
    res.status = True
    return JsonResponse(res.dict)

#短信验证码验证

def sms_login(request):
    if request.method == "GET":
        form = SmsForms()
        return render(request, 'sms_login.html',{"form":form})
    form = SmsLoginForms(data=request.POST)
    # mobile = form.cleaned_data['mobile']
    # code = form.cleaned_data['code']
    #手机格式验证
    res = BaseResponse()
    if not form.is_valid():
        res.detail = form.errors
        return JsonResponse(res.dict,json_dumps_params={'ensure_ascii': False})

    role = form.cleaned_data['role']
    mobile = form.cleaned_data['mobile']
    print("------>",form.clean_code())
    if role == "1":
        user_objects = models.Administrator.objects.filter(active=1,mobile=mobile).first()
    else:
        user_objects = models.Customer.objects.filter(active=1,mobile=mobile).first()
    if not user_objects:
        res.detail = {"mobile":"手机号不存在"}

    mapping = {"1": "ADMIN", "2": "CUSTOMER"}
    request.session['user_info'] = {'role': mapping[role], 'name': user_objects.name, 'id': user_objects.id}
    return redirect("/home/")
def logout(request):
    request.session.clear()
    return redirect("/login/")
def home(request):
    return render(request,'home.html')























# def level(request):
#     form = AddLevelForms()
#     res = models.Leval.objects.all()
#     data = request.POST
#     # title = form.cleaned_data.get("title")
#     if data:
#         title = data.get("title")
#         present = data.get("present")
#         level_add(title,present)
#         res = models.Leval.objects.all()
#     return render(request, 'level.html',{"form": form, "res": res})
# def level_add(title,present):
#     models.Leval.objects.create(title=title,present=present)
#
# @require_http_methods(["DELETE"])
# def delete_level(request,item_id):
#     # 根据传递的item_id执行删除操作
#     try:
#         # 假设有一个名为Item的模型，用来表示要删除的对象
#         item = models.Leval.objects.get(pk=item_id)
#         item.delete()
#         return JsonResponse({"message": "删除成功"})
#     except models.Leval.DoesNotExist:
#         return JsonResponse({"error": "该项目不存在"}, status=404)
#     except Exception as e:
#         return JsonResponse({"error": f"删除时发生错误: {str(e)}"}, status=500)
#
# def edit_level(request):
#     data = models.Leval.objects.filter(id=request.GET.get("item_id")).first()
#     return render(request, 'edit_level.html',{"id": request.GET.get("item_id"),"title": data.title, "present": data.present})
#
# def edit(request):
#     if request.method == 'POST' and request.is_ajax():
#         item_id = request.POST.get('item_id')
#         # 在这里处理收到的item_id
#         # 你可以从数据库中获取数据进行编辑
#         # 保存编辑后的数据
#         # 假设这里直接返回成功的响应
#         return JsonResponse({'success': True})
#     else:
#         return JsonResponse({'success': False, 'error': 'Invalid request'})
#
#
# def level_saveitem(request):
#     id = request.POST.get('id')
#     title = request.POST.get('level')
#     present = request.POST.get('discount')
#     models.Leval.objects.filter(id=id).update(title=title, present=present)
#     return render(request,"level.html")